const { read, write } = require('../lib/read&write')

const ARTICLEURL = '../data/articles.json'
function setArticle(article) {
  const __Article = read(ARTICLEURL)
  __Article.push(article)
  write(__Article, ARTICLEURL)
}

function editArticle(article) {
  const __Article = read(ARTICLEURL)
  __Article.splice(
    __Article.findIndex((item) => item.id == article.id),
    1,
    article,
  )
  write(__Article, ARTICLEURL)
}

function deleteArticle(articleId) {
  const __Article = read(ARTICLEURL)
  let targetArticle = searchArticle(articleId)
  __Article.splice(
    __Article.findIndex((item) => item.id == targetArticle.id),
    1
  )
  write(__Article, ARTICLEURL)
}

function getAllArticles() {
  const __Article = read(ARTICLEURL)
  return __Article
}

function searchArticle(articleId) {
  const __Article = read(ARTICLEURL)
  return __Article.find((item) => item.id === articleId)
}

module.exports = {
  searchArticle,
  getAllArticles,
  editArticle,
  setArticle,
  // 以下未用
  deleteArticle,
}
